import {Component} from "@angular/core";
import {AlertController, LoadingController, NavController, NavParams} from "ionic-angular";
import {WorkTypePage} from "../worktype/worktype";
import {MainceHistory} from "../maince-history/maince-history";
import {RepairHistory} from "../repair-history/repair-history";
import {CheckHistory} from "../check-history/check-history";
import {HelpHistory} from "../help-history/help-history";
import {FeedbackPage} from "../feedback/feedback";
import {appConfig, constant} from "../../providers/config";
import {Observable} from "rxjs/Observable";
import "rxjs/add/observable/forkJoin";
import "rxjs/add/observable/from";
import {HttpService} from "../../providers/http.service";
import {RepairApplyList} from "../repair-apply-list/repair-apply-list";
import {EmergencyrescuePage} from "../emergencyrescue/emergencyrescue";
import {DailyInspectionPage} from "../daily-inspection/daily-inspection";
import {EmergencyEventListPage} from "../emergency-event-list/emergency-event-list";
import {RescuDrillPage} from "../rescue-drill/rescue-drill";
import {RepairListPage} from "../used-repair/repair-list/repair-list";
import {ApplyRepairPage} from "../repair-apply/apply-repair";
import {Storage} from "@ionic/storage";
import {CommonFunc} from "../../providers/commonFunc";
import {DailyInspectionFtPage} from "../daily-inspection-ft/daily-inspection-ft";
import {DailyHistory} from "../daily-history/daily-history";
import {CheckItemDetail} from "../supervision/check-item-detail/check-item-detail";
import {maintenanceBeforePage} from "../maince-type/maintenance-before/maintenanceBefore";

import {SelfCheckTractionPage} from "../selfcheck/self-check-traction/self-check-traction";
import {SelfCheckHydraulicPage} from "../selfcheck/self-check-hydraulic/self-check-hydraulic";
import {SelfCheckImpurityPage} from "../selfcheck/self-check-impurity/self-check-impurity";
import {SelfCheckEscalatorPage} from "../selfcheck/self-check-escalator/self-check-escalator";
@Component({
  templateUrl: "elevator-detail.html"
})
export class EleDetailPage {
  private isPassenger: boolean = false; //是否是乘客
  private elevatorNum: string;
  private elevatorId: string;
  private buildAddr: string;
  private elevatorIdInfo: any = {};
  private repairList: any = [];
  private emergencyList: any = [];
  private maintenceList: any = [];
  private dailyList: any = [];
  private elevatorType: string;
  private workType: string;
  showToWork = true;
  private elevatorTypes = [
    {
      label: "载客电梯",
      value: "1"
    },
    {
      label: "液压驱动电梯",
      value: "2"
    },
    {
      label: "杂物电梯",
      value: "3"
    },
    {
      label: "自动扶梯",
      value: "4"
    },
    {
      label: "载物电梯",
      value: "5"
    },
    {
      label: "自动人行道",
      value: "6"
    }
  ];
  private maintenceTypes = constant.maintenceTypes;

  constructor(
    public navCtrl: NavController,
    private alertCtrl: AlertController,
    private navParams: NavParams,
    private loading: LoadingController,
    private httpService: HttpService,
    private storage: Storage,
    private commonFunc: CommonFunc
  ) {
    try {
      this.isPassenger = navParams.get("isPassenger");
      this.elevatorNum = navParams.get("elevatorNum");
      this.elevatorId = navParams.get("elevatorId");
      this.elevatorType = navParams.get("elevatorType");
      this.workType = navParams.get("workType");
      if (
        this.workType == null ||
        this.workType == "" ||
        this.workType == undefined
      ) {
        this.showToWork = false;
      }
      let load = this.loading.create({
        spinner: appConfig.spinner,
        duration: appConfig.timeout
      });

      load.present();
      let observable = Observable.forkJoin([
        //查询电梯
        Observable.from(
          this.httpService.queryElevatorInfo({ id: this.elevatorId })
        ),
        Observable.from(this.httpService.queryElevatorType({}))
      ]);
      observable.subscribe(data => {
        load.dismiss();
        //电梯信息
        if (data[0].status == 200) {
          this.elevatorIdInfo = data[0].data;
          this.buildAddr = this.elevatorIdInfo.buildAddr;
          //判断有没有权限工作-------ssr--------
          storage.get("user").then(data => {
            //账号封停状态直接不给工作
            if (data.userState == 0) {
              this.showToWork = false;
              return;
            }
            if (data.partyType == "1") {
              this.showToWork =
                data.partyId == this.elevatorIdInfo.maintenancePartyId;
              if (!this.showToWork) {
                let toas = this.commonFunc.showToast({
                  message: "不是贵公司负责的电梯!",
                  duration: 5000,
                  position: "top"
                });
                toas.present();
              }
            } else if (data.partyType == "2") {
              this.showToWork = data.partyId == this.elevatorIdInfo.usedPartyId;
              if (!this.showToWork) {
                let toas = this.commonFunc.showToast({
                  message: "不是贵公司负责的电梯!",
                  duration: 5000,
                  position: "top"
                });
                toas.present();
              }
            }else if (data.partyType =="4") {
               this.showToWork =true;
            } else {
              this.showToWork = false;
            }
          });
          //---------------ssr-----20180506-------------

          //查询机构
          this.httpService
            .queryPartyById({ id: this.elevatorIdInfo.maintenancePartyId })
            .subscribe(data => {
              if (data.status == 200) {
                if (data.data) {
                  this.elevatorIdInfo.maintenancePartyName =
                    data.data.partyName;
                }
              }
            });
        }
        //电梯类型
        if (data[1].status == 200) {
          data[1].data.list.forEach(elevatorType => {
            if (elevatorType.id == this.elevatorIdInfo.elevatorTypeId) {
              this.elevatorIdInfo.elevatorTypeName = elevatorType.typeName;
            }
          });
        }
      });

      if (!this.isPassenger) {
        let observable2 = Observable.forkJoin([
          Observable.from(
            this.httpService.queryRepairList({
              elevatorId: this.elevatorId,
              pageSize: 3,
              currentPage: 1
            })
          ),
          // Observable.from(
          //   this.httpService.queryEmergencyList({
          //     elevatorId: this.elevatorId,
          //     pageSize: 3,
          //     currentPage: 1
          //   })
          // )
        ]);
        observable2.subscribe(data => {
          if (data[0].status == 200) {
            this.repairList = data[0].data.list;
          }

          // if (data[1].status == 200) {
          //   this.emergencyList = data[1].data.list;
          // }
        });

        //巡检
        this.httpService.getInspectionList({
          elevatorId: this.elevatorId,
          pageSize: 3,
          currentPage: 1
        }).subscribe(data => {
          if (data.status == 200) {
            this.dailyList = data.data.list;
          }
        })

        //维保记录列表
        let ob: any;
        if (this.elevatorType == "1" || this.elevatorType == "5") {
          ob = this.httpService.queryTraction({
            elevatorNum: this.elevatorNum,
            pageSize: 3,
            currentPage: 1
          });
        }
        if (this.elevatorType == "2") {
          ob = this.httpService.queryHydpress({
            elevatorNum: this.elevatorNum,
            pageSize: 3,
            currentPage: 1
          });
        }
        if (this.elevatorType == "3") {
          ob = this.httpService.queryDebris({
            elevatorNum: this.elevatorNum,
            pageSize: 3,
            currentPage: 1
          });
        }
        if (this.elevatorType == "4" || this.elevatorType == "6") {
          ob = this.httpService.queryEscalator({
            elevatorNum: this.elevatorNum,
            pageSize: 3,
            currentPage: 1
          });
        }
        ob.subscribe(data => {
          this.maintenceList = data.data.list;
        });
      }
    } catch (e) {
    }
  }
  // 去工作
  goWork() {
    try {
      let workType = this.workType;
      let data = new Date().getTime();
      switch (workType) {
        case "1":
        case "2":
        case "3":
        case "4":
         //跳转到作业前页面
            this.navCtrl.push(maintenanceBeforePage , {
                ElevaType: this.elevatorType,
                type: workType,
                elevatorNum: this.elevatorNum,
                elevatorInfo: this.elevatorIdInfo,
                isPassenger : this.navParams.get("isPassenger"),
            });
          // debugger;
          /*if (this.elevatorType == "1" || this.elevatorType == "5") {
            //工曳电梯
            this.navCtrl.push(TractionPage, {
              ElevaType: this.elevatorType,
              type: workType,
              elevatorNum: this.elevatorNum,
              elevatorInfo: this.elevatorIdInfo,
              data: data
            }); //跳转 （月--年）保
          }
          if (this.elevatorType == "2") {
            //液压
            this.navCtrl.push(HydpressPage, {
              ElevaType: this.elevatorType,
              type: workType,
              elevatorNum: this.elevatorNum,
              elevatorInfo: this.elevatorIdInfo,
              data: data
            }); //跳转 （月--年）保
          }
          if (this.elevatorType == "3") {
            //杂物
            this.navCtrl.push(DebrisPage, {
              ElevaType: this.elevatorType,
              type: workType,
              elevatorNum: this.elevatorNum,
              elevatorInfo: this.elevatorIdInfo,
              data: data
            }); //跳转 （月--年）保
          }
          if (this.elevatorType == "4" || this.elevatorType == "6") {
            //自动扶梯
            this.navCtrl.push(EscalatorPage, {
              ElevaType: this.elevatorType,
              type: workType,
              elevatorNum: this.elevatorNum,
              elevatorInfo: this.elevatorIdInfo,
              data: data
            }); //跳转 （月--年）保
          }*/
          break;
        case "5":
          // this.navCtrl.push(RepairInfoPage,this.navParams);//跳转维修
          this.navCtrl.push(RepairApplyList, this.navParams); //跳转维修列表
          break;
        case "6":
          this.navCtrl.push(EmergencyrescuePage, this.navParams); //跳转应急救援
          break;
        case "7":
          console.log("年度自保");
          break;
        case "8":
          console.log("定期检查");
          break;
        case "9":
          if (this.elevatorType == "4" || this.elevatorType == "6") {
            this.navCtrl.push(DailyInspectionFtPage, {
              elevatorId: this.elevatorId,
              elevatorInfo: this.elevatorIdInfo,
              data: new Date(),
            }); //跳转巡检页面
          } else {
            this.navCtrl.push(DailyInspectionPage, {
              elevatorId: this.elevatorId,
              elevatorInfo: this.elevatorIdInfo,
              data: new Date(),
            }); //跳转巡检页面
          }

          break;
        case "0":
          this.navCtrl.push(EmergencyEventListPage, {
            elevatorId: this.elevatorId,
            elevatorNum: this.elevatorNum
          }); //跳转应急救援
          break;
        case "10":
          this.navCtrl.push(RescuDrillPage); //救援演练
          break;
        case "11":
          this.navCtrl.push(RepairListPage); //维修（物业）
          break;
        case "12":
          this.navCtrl.push(ApplyRepairPage, {
            applyType: "1",
            elevatorId: this.elevatorId,
            elevatorNum: this.elevatorNum,
            buildAddr: this.buildAddr
          }); //报修（维保）
          break;
        case "13":
          this.navCtrl.push(ApplyRepairPage, {
            applyType: "2",
            elevatorId: this.elevatorId,
            elevatorNum: this.elevatorNum,
            buildAddr: this.buildAddr
          }); //招修（物业）
          break;
        case "14":
          this.navCtrl.push(RescuDrillPage, {
            // applyType: "2",
            elevatorId: this.elevatorId,
            elevatorNum: this.elevatorNum
          }); //救援演练
          break;
        case "15":
          if(this.elevatorType == '1' || this.elevatorType == '5'){ //曳引
            this.navCtrl.push(SelfCheckTractionPage, {
              elevatorId: this.elevatorId,
              elevatorNum: this.elevatorNum,
              elevatorType: this.elevatorType
            });
          }else if(this.elevatorType == '4' || this.elevatorType == '6'){ //自动扶梯
            this.navCtrl.push(SelfCheckEscalatorPage, {
              elevatorId: this.elevatorId,
              elevatorNum: this.elevatorNum,
              elevatorType: this.elevatorType
            });
          }else if(this.elevatorType == '3'){//杂物
            this.navCtrl.push(SelfCheckImpurityPage, {
              elevatorId: this.elevatorId,
              elevatorNum: this.elevatorNum,
              elevatorType: this.elevatorType
            });
          }else if(this.elevatorType == '2'){//液压
            this.navCtrl.push(SelfCheckHydraulicPage, {
              elevatorId: this.elevatorId,
              elevatorNum: this.elevatorNum,
              elevatorType: this.elevatorType
            });
        }
           //年度自检
          break;
        case "check":
            this.navCtrl.push(CheckItemDetail, {
                elevatorId: this.elevatorId,
                elevatorNum: this.elevatorNum,
                elevatorType: this.elevatorType,
                id:this.navParams.get("id"),
                type:this.navParams.get("type"),
                state: this.navParams.get("state"),
                beCkedPartyName: this.navParams.get("beCkedPartyName"),
                beCkedPartyId: this.navParams.get("beCkedPartyId"),
                pdType: this.navParams.get("pdType"),
                pdId:this.navParams.get("pdId"),
            });
      }
    } catch (e) { }
  }
  toSign() {//废弃不用了
    this.navCtrl.push(WorkTypePage, {
      elevatorType: this.elevatorType,
      elevatorNum: this.elevatorNum,
      elevatorId: this.elevatorId,
      elevatorInfo: this.elevatorIdInfo
    });
  }
  /**
   * 跳转维保记录全部
   */
  toMaince() {
    this.navCtrl.push(MainceHistory, {
      elevatorType : this.elevatorType,
      elevatorNum : this.elevatorNum,
      elevatorId : this.elevatorId,
    });
  }

  toDaily() {
    this.navCtrl.push(DailyHistory, {
      elevatorId: this.elevatorId
    });
  }


  toRepair() {
    this.navCtrl.push(RepairHistory, { elevatorId: this.elevatorId });
  }
  toCheck() {
    this.navCtrl.push(CheckHistory);
  }
  toHelp() {
    this.navCtrl.push(HelpHistory, { elevatorId: this.elevatorId });
  }

  doCall() {
    const alert = this.alertCtrl.create({
      title: "紧急救援电话",
      message: appConfig.emergencyPhone,
      buttons: [
        {
          text: "取消",
          role: "cancel",
          handler: () => {
            console.log("Cancel clicked");
          }
        },
        {
          text: "确认",
          handler: () => {
            window.location.href = "tel://" + appConfig.emergencyPhone;
          }
        }
      ]
    });
    alert.present();
  }
  toFeedback() {
    this.navCtrl.push(FeedbackPage);
  }
}
